import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { VideoEntity } from '@/api/manager/liveVideo/interface'
import dayjs from '@/plugins/dayjs'
import { useMccStore } from '../../store'

type StateStore = VideoEntity
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	ws: {
		mcc_message_recordrec_status: (params: Partial<VideoEntity>) => void
	}
}
export function getRecFileName(name?: string) {
	if (name) {
		if (name.endsWith('.asf')) {
			return name.slice(0, -4)
		} else {
			return name
		}
	} else {
		const subject = useMccStore.getState().mccInfo.subject
		return subject.substring(0, 26) + dayjs().format('YYYYMMDDHHmmss')
	}
}
const initialState: StateStore = {
	vrs_id: '',
	vrs_name: '',
	id: '',
	rec_id: '0',
	duration: '',
	rec_file: getRecFileName(),
	live_url: '',
	live_qr_code: '',
	live_password: '',
	publish_mode: 0,
	watermark: 0,
	state: 0,
	recorder_mode: 0,
	anonymous: 0,
	dual_stream: 1,
	main_stream: 1,
}
export const useLiveVideoStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		ws: {
			mcc_message_recordrec_status: (params) => {
				if (params.state === 0) {
					set({
						...initialState,
						rec_file: getRecFileName(params.rec_file),
						live_password: params.live_password || '',
						live_url: params.live_url || '',
						live_qr_code: params.live_qr_code || '',
						vrs_id: params.vrs_id || '',
					})
				} else {
					//处理几个input和checkbox，因为推送过来，会覆盖人为操作的内容
					if (params.recorder_mode === 1) {
						delete params['live_password']
						delete params['anonymous']
					} else if (params.recorder_mode === 2) {
						delete params['anonymous']
					}
					set({
						...params,
						rec_file: getRecFileName(params.rec_file),
					})
				}
			},
		},
	}))
)
